<?php

namespace app\admin\controller;

use app\common\helper\Tree;
use \think\Controller;
use \think\Request;
use \think\Db;

class BaseController extends Controller
{
    protected $request, $param, $module, $controller, $action, $id, $pageSize, $url, $do_url, $currentUser;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->param = $this->request->param();
        $this->module = $request->module();
        $this->controller = $request->controller();
        $this->action = $request->action();
        $this->pageSize = 10;
        $this->do_url = $this->parseName($this->module) . "/" . $this->parseName($this->controller) . "/";
        $this->url = $this->parseName($this->module) . '/' . $this->parseName($this->controller) . "/" . $this->parseName($this->action);
        $this->currentUser = "currentUser";
        parent::__construct();
    }

    public function initialize()
    {
        $tree = $this->getMenuList(); // 获取权限列表
        $menuTree = $this->getMenuTreeHtml($tree);
        $this->assign('tree', $menuTree);
    }

    /**
     * 获取权限列表
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getMenuList()
    {
        $menuArr = Db::table('aya_menu')->where('menu_status', '=', 1)
            ->where('menu_is_admin', '=', 1)
            ->where('menu_depth', '<', 4)
            ->order('menu_sort', 'asc')
            ->order('create_time', 'desc')
            ->select();
        Tree::setConfig('menu_id', 'menu_parent_id');
        $result = Tree::makeTree($menuArr);
        return $result;
    }

    /**
     * 后台验证后返回信息
     * @param string $msg
     * @param string $icon
     * @param null $url
     * @param string $data
     */
    protected function doRedirect($msg = '', $icon = "2", $url = null, $data = '')
    {
        $server = $this->request->server();
        if ($url == null && isset($server['HTTP_REFERER'])) {
            $url = $server['HTTP_REFERER'];
        }
        if ($this->url == '' || $url == null) {
            $msg = '页面不存在！';
            $url = 'admin/index/index';
        }
        $this->redirect($url, $data, 302, ['error_message' => $msg . '|' . $icon, 'form_info' => $this->param]);
    }

    /**
     * 字符串命名风格转换
     * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
     * @param $name 字符串
     * @param int $type 转换类型
     * @param bool $first 首字母是否大写（驼峰规则）
     * @return string
     */
    protected function parseName($name, $type = 0, $first = true)
    {
        if ($type) {
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $name);
            return $first ? ucfirst($name) : lcfirst($name);
        } else {
            return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
        }
    }

    private function getMenuTreeHtml($menuTree)
    {
        $tree = '';
        if (empty($menuTree)) {
            return $tree;
        }
        $active = '';
        $currentUrl = strtolower($this->controller . '/' . $this->action);
        if ('index/index' == $currentUrl) {
            $active = 'active';
        }
        $tree .= '<li class="' . $active . '"><a href="' . url('index/index') . '"><i class="fa fa-home"></i><span>首页</span></a></li>';
        foreach ($menuTree as $key => $menu) {
            $treeChild = '<ul class="treeview-menu">';
            //第二级别菜单判断
            if (!empty($menuTree[$key]['child'])) {
                foreach ($menuTree[$key]['child'] as $child) {
                    $active = '';
                    if ($child['menu_page_url'] == $currentUrl) {
                        $active = 'active';
                    }
                    //第三级别菜单判断
                    if (!empty($child['child'])) {
                        foreach ($child['child'] as $grandChild) {
                            if ($grandChild['menu_page_url'] == $currentUrl) {
                                $active = 'active';
                            }
                        }
                    }
                    $treeChild .= '<li class="' . $active . '"><a href="' . url($child['menu_page_url']) . '"><i class="' . $child['menu_icon'] . '"></i>' . $child['menu_name'] . '</a></li>';
                }
            }
            $treeChild .= '</ul>';
            $tree .= '<li class="treeview ' . $active . '"><a href="javascript:"><i class="' . $menu['menu_icon'] . '"></i><span>' . $menu['menu_name'] . '</span><span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span></a>';
            $tree .= $treeChild;
            $tree .= '</li>';
        }
        return $tree;
    }

    public function _empty()
    {
        $this->error('页面不存在');
    }
}